<template>
    <div class="planList-index yuan-container">
        <div class="filter-panel">
            <span class="planList-title">
                {{planSimulation.planName}}
            </span>
            <div class="filter-list">
                <span class="filter-tips ">实际投料量：
                    <span class="font-bignum c-primary">{{(pageData.touliao  )|| '--' }}</span>
                    <span>kg</span>
                </span>
            </div>
        </div>

        <div class="planList-top filter-panel" v-for="item in alarmDataCopy">
            <span class="planList-title">
                {{item.inventoryType}}
            </span>
            <div class="filter-list">
                <span class="filter-tips">预计产出时间：
                    <span class="mast-ico"></span>
                    <a-date-picker class="yuan-form-input" @change="planTimeChange(item,$event)" placeholder="预计产出时间" v-model="item.planTime" valueFormat="YYYY-MM-DD" />
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">完成天数：
                    <span class="mast-ico"></span>
                    <a-input-number class="yuan-form-input" @change="finishDayChange(item,$event)" placeholder="完成天数" v-model="item.finishDay"/>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">预计完成时间：
                    <span class="mast-ico"></span>
                    <a-date-picker class="yuan-form-input" placeholder="预计完成时间" v-model="item.finishTime"
                        valueFormat="YYYY-MM-DD" disabled/>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">实际包装量：<span class="mast-ico"></span></span>
                <a-input v-model="item.prodNum" placeholder="实际包装量" @input="proNumChange" />
            </div>
            
            <div class="filter-list">
                <span class="filter-tips">配方颗粒(颗粒)需求量：<span class="mast-ico"></span></span>
                <a-input v-model="item.needNum" placeholder="配方颗粒(颗粒)投入量" @input="needNumChange" />
            </div>
            <div class="filter-list">
                <span class="filter-tips">装量：<span class="mast-ico"></span></span>
                <span >{{item.loadingQuantity}}</span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">预计包装后成品可销售天数：{{item.packSellDay}}天</span>
            </div>
        </div>

        <div style="border-bottom:solid 1px #999;margin-bottom:20px"></div>
        <div class="filter-panel" style="display:flex;align-items: center;margin-bottom:20px">
            <div class="filter-list">
                <span class="filter-tips" style="font-size:16px;font-weight:bold;">
                    {{planSimulation.materialName}} 库存现状
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips ">颗粒库存总数量：
                    <span class="font-bignum c-primary">{{stockTotal |toDecimalNoZero }}</span>
                    <span>kg</span>
                </span>
                <span class="filter-tips ">记录结存量：
                    <span class="font-bignum c-primary">{{storageRecordWeight || '--'}}</span>
                    <span>kg</span>
                </span>
            </div>
        </div>

        <template v-if="pageData.useStore===true">

            <div class="filter-panel">
                <div class="filter-list">
                    <span>颗粒批号：</span>
                    <a-input-search allowClear v-model="pageParams.batch" placeholder="请输入颗粒批号" @search="resetList" />
                </div>
                <!-- <div class="filter-list">
                    <span>可供销售天数：</span>
                    <span class="filter-range">
                        <a-input v-model="pageParams.sellDayStart"></a-input>
                        <span class="filter-tips">~</span>
                        <a-input v-model="pageParams.sellDayEnd"></a-input>
                        <span class="filter-tips">天</span>
                    </span>
                </div>
                <div class="filter-list">
                    <span>质量状态：</span>
                    <a-select v-model="pageParams.qualityState" @change="resetList" allowClear placeholder="请选择质量状态">
                        <a-select-option value="1">合格</a-select-option>
                        <a-select-option value="2">不合格</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span>有效期：</span>
                    <a-range-picker :mode="['month','month']" :open="monthPickShow" @panelChange="handlePanelChange"
                        v-model="billMonth" @openChange="handleOpenChange" :placeholder="['开始日期','结束日期']"
                        :format="['YYYY-MM','YYYY-MM']" />
                </div> -->
                <div class="filter-list">
                    <a-button type="primary" @click="getList" class="filter-list">搜索</a-button>
                </div>
            </div>
            <a-tabs v-model="tabActive" @change="tabChange">
                <a-tab-pane key="制粒" tab="制粒"></a-tab-pane>
                <a-tab-pane key="总混二" tab="总混二"></a-tab-pane>
            </a-tabs>
            <div class="table" v-if="tabActive=='制粒'">
                <a-radio-group v-model="tableSelect" @change="pageListSelectChange" style="width:100%">
                    <a-table bordered :rowKey="(row)=>row.id" :pagination="false" :data-source="pageList" :columns="packageColumns" :loading="loading">
                        <template slot="select" slot-scope="text, record, index">
                            <a-radio :value="index" :checked="record.isSelect"></a-radio>
                        </template>
                        <template :slot="'number'+item.inventoryType+item.loadingQuantity" slot-scope="text, record, index"
                            v-for="(item,i) in alarmDataCopy">
                            <span v-if="!pageList[index].isSelect || item.formDifferenceNum<=0">--</span>
                            <a-input type="number" style="width:100px" placeholder="请输入数量"
                                v-model="pageList[index][item.inventoryType+'_num'+item.loadingQuantity]" @input="inputNumChange" v-else />
                        </template>
                    </a-table>
                </a-radio-group>
            </div>
            <div class="table" v-else>
                <a-radio-group v-model="tableSelect" @change="pageListSelectChange" style="width:100%">
                    <a-table bordered :rowKey="(row)=>row.id" :pagination="false" :data-source="pageList" :columns="packageColumns" :loading="loading">
                        <template slot="select" slot-scope="text, record, index">
                            <a-radio :value="index" :checked="record.isSelect"></a-radio>
                        </template>
                        <template :slot="'number'+item.inventoryType+item.loadingQuantity" slot-scope="text, record, index"
                            v-for="(item,i) in alarmDataCopy">
                            <span v-if="!pageList[index].isSelect || item.formDifferenceNum<=0">--</span>
                            <a-input type="number" style="width:100px" placeholder="请输入数量"
                                v-model="pageList[index][item.inventoryType+'_num'+item.loadingQuantity]" @input="inputNumChange" v-else />

                        </template>
                    </a-table>
                </a-radio-group>
            </div>
        </template>

    </div>
</template>
<script lang="ts">
import nextApi from "@/api/nextApi";
import warningApi from "@/api/warningApi";
import { toDecimalNoZero } from "@/utils";
import { ColumnGroup } from "ant-design-vue/types/table/column-group";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";

@Component({
    name: "dom",
    components: {},
})
export default class index extends Vue {
    @Prop({ default: "" }) planSimulation!: any;
    @Prop({ default: "" }) alarmData!: any;
    alarmDataCopy: any[] = [];
    packageColumns = [];
    tabActive = "制粒"
    // 包装计划表格
    packageColumnsDef = [
        {
            align: "center",
            dataIndex: "select",
            key: "select",
            title: "",
            scopedSlots: { customRender: "select" },
        },
        {
            align: "center",
            dataIndex: "zlBatch",
            key: "zlBatch",
            title: "颗粒批号",
        },
        {
            align: "center",
            dataIndex: "zlProdTime",
            key: "zlProdTime",
            title: "生产日期",
        },
        // {
        //     align: "center",
        //     dataIndex: "validTime",
        //     key: "validTime",
        //     title: "有效期至",
        // },
        {
            align: "center",
            dataIndex: "zlRecheckTime",
            key: "zlRecheckTime",
            title: "复验期",
        },
        {
            align: "center",
            dataIndex: "zlBalanceWeight",
            key: "zlBalanceWeight",
            title: "库存数量",
            // customRender: (text: string, record: any, index: number) => toDecimalNoZero(record.surplus, 2),
        },
        {
            align: "center",
            dataIndex: "zlQualityState",
            key: "zlQualityState",
            title: "质量状态",
        },
        {
            align: "center",
            dataIndex: "recordWeight",
            key: "recordWeight",
            title: "记录数量",
        },
    ];
    loading = false;
    pageParams: any = {
        batch: "",
        qualityState: undefined,
        sellDayStart: "",
        sellDayEnd: "",
        startTime: "",
        endTime: "",
    };
    pagination = {
        pageSize: 999,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    pageList: any[] = [];
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    stockTotal = 0;
    storageRecordWeight = 0
    async getList() {
        this.tableSelect = "";
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getPowderStorage({
                // ...this.pageParams,
                name:this.alarmData[0].materialName,
                standard:this.alarmData[0].standard,
                pageSize: this.pagination.pageSize,
                page: this.pagination.current,
                // materialName: this.planSimulation.materialName,
                // materialType: "配方颗粒（颗粒）",
                type2:this.tabActive
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.list || [];
            this.stockTotal = res.data?.total || 0
            this.storageRecordWeight = res.data?.storageRecordWeight || 0
            // let stockTotal = 0;
            // this.pageList.forEach((item) => {
            //     stockTotal += Number(item.surplus || 0);
            // });
            // this.stockTotal = stockTotal;

            // 还原以前的投料信息
            this.alarmDataCopy.forEach((alarm) => {
                
                if (alarm.processPlanInputNewList?.length > 0) {
                    const listOne = alarm.processPlanInputNewList[0];
                    this.pageList.forEach((item, idx) => {
                        if (item.id === listOne.stockId) {
                            item.isSelect = true;
                            item[alarm.inventoryType + "_num"+item.loadingQuantity] = listOne.inputNum;
                            this.tableSelect = idx;
                        }
                    });
                    this.inputNumChange();
                }
            });
            if(this.pageList.length == 0){
                this.$message.warning('该品种颗粒(颗粒)暂无库存、请在半成品库存表-总混二、制粒添加库存信息')
            }
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    tabChange(v){
        if(v==='总混二'){
            this.packageColumnsDef[2].key = 'zheInTime'
            this.packageColumnsDef[2].dataIndex = 'zheInTime'
            this.packageColumnsDef[4].key = 'zheBalanceWeight'
            this.packageColumnsDef[4].dataIndex = 'zheBalanceWeight'
            this.packageColumnsDef[3].key = 'zheRecheckTime'
            this.packageColumnsDef[3].dataIndex = 'zheRecheckTime'
            this.packageColumnsDef[5].key = 'zheQualityState'
            this.packageColumnsDef[5].dataIndex = 'zheQualityState'
        }else{
            this.packageColumnsDef[2].key = 'zlProdTime'
            this.packageColumnsDef[2].dataIndex = 'zlProdTime'
            this.packageColumnsDef[4].key = 'zlBalanceWeight'
            this.packageColumnsDef[4].dataIndex = 'zlBalanceWeight'
        }
       // 重新生成 packageColumns
        const newArr = JSON.parse(JSON.stringify(this.packageColumnsDef));
        this.alarmDataCopy.forEach((item) => {
            newArr.push({
                align: "center",
                dataIndex: "inventoryType" + item.inventoryType + item.loadingQuantity,
                key: "inventoryType" + item.inventoryType + item.loadingQuantity,
                title: item.inventoryType + "投料量（kg）" + '装量：' + item.loadingQuantity,
                scopedSlots: { customRender: "number" + item.inventoryType + item.loadingQuantity },
            });
        });
        this.packageColumns = newArr;
        this.tableSelect = ''
        this.getList()
    }
    billMonth = [];
    monthPickShow = false;
    handlePanelChange(value, mode) {
        if (mode[1] === "date") {
            const arr = value.map((item) => item.format("YYYY-MM"));
            this.billMonth = arr;
            this.pageParams.startTime = arr[0];
            this.pageParams.endTime = arr[1];
            this.resetList();
            this.monthPickShow = false;
        }
    }
    handleOpenChange(status) {
        if (status) {
            this.monthPickShow = true;
        } else {
            this.monthPickShow = false;
        }
    }

    tableSelect: any = "";
    pageListSelectChange() {
        if (this.tableSelect === "") return;

        const pageList = [...this.pageList];
        const type = pageList[this.tableSelect].isSelect;
        pageList.map((item) => {
            item.isSelect = false;
        });
        if (!type) {
            pageList[this.tableSelect].isSelect = true;
        }
        this.pageList = pageList;
        this.inputNumChange();
        
    }

    planTimeChange(item,v){
        if(v){
            let time = new Date(v).getTime()
            console.log(time);
            if(item.finishDay){
                let oneDayTimeStamp = 24*60*60*1000
                let finishTimeStamp = time + (item.finishDay*oneDayTimeStamp)
                item.finishTime = new Date(finishTimeStamp).toLocaleDateString()
            }
        }
    }
    finishDayChange(item,v){
        if(v){
            if(item.planTime){
                let planTimeStamp = new Date(item.planTime).getTime()
                let oneDayTimeStamp = 24*60*60*1000
                let finishTimeStamp = planTimeStamp + (v*oneDayTimeStamp)
                item.finishTime = new Date(finishTimeStamp).toLocaleDateString()
            }
        }
    }

    pageData: any = {
        useStore: true,
        touliao: "",
        shenchan: "",
    };
    mounted() {
        
        const newArr = JSON.parse(JSON.stringify(this.packageColumnsDef));
        this.alarmDataCopy = JSON.parse(JSON.stringify(this.alarmData));
        this.alarmDataCopy.forEach((item) => {
            if(!item.needNum) item.needNum=item.inputNum
            newArr.push({
                align: "center",
                dataIndex: "inventoryType" + item.inventoryType+item.loadingQuantity,
                key: "inventoryType" + item.inventoryType+item.loadingQuantity,
                title: item.inventoryType + "投料量（kg）"+'装量：'+item.loadingQuantity,
                scopedSlots: { customRender: "number" + item.inventoryType+item.loadingQuantity },
            });
        });
        this.packageColumns = newArr;
        this.getList();
    }
    simulationTimer: number | null = null;
    inputNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        if (this.tableSelect === "") return;
        this.simulationTimer = setTimeout(async () => {
            let total = 0;
            this.alarmData.forEach((item) => {
                // 拼接 inventoryType+_num+loadingQuantity
                total += Number(this.pageList[this.tableSelect][item.inventoryType + "_num" + item.loadingQuantity]) || 0;
            });
            if (total > this.pageList[this.tableSelect].surplus) {
                this.$message.error("投料数量不能大于库存量");
                return;
            }

            this.pageData.touliao = toDecimalNoZero(total);
        }, 500);
    }
    getPageInfo() {
        let verfyType = true;
        let verfyWords = "";
        let processPlanDetailList: any[] = [];
        // 没有库存的情况暂不考虑

        // 如果使用当前库存

        const item = this.pageList[this.tableSelect];
        if (!item) {
            this.$message.error("包装计划还没有选择投料");
            return false;
        }

        let total = 0;
        
        this.alarmDataCopy.forEach((alarmDataItem) => {
            if (!alarmDataItem.finishTime) {
                verfyType = false;
                verfyWords = "请选择包装计划预计完成时间";
            }
            // 拼接 inventoryType+_num+loadingQuantity
            const num = item[alarmDataItem.inventoryType + "_num" + alarmDataItem.loadingQuantity];
            total += Number(num) || 0;
            let processPlanInputList = [
                {
                    ...alarmDataItem,
                    detailId:alarmDataItem.id,
                    stockId: item.id,
                    isPro: true,
                    batch: item.zlBatch,
                    inputNum: num,
                    type:'制粒',
                    inputName:item.zlName,
                    productDate:item.zlProdTime,
                    recheckDate:item.zlRecheckTime,
                    storageNum:item.zlBalanceWeight,
                    qualityState:item.zlQualityState,
                    
                    materialName: item.materialName,
                    materialType: item.materialType,
                    materialId: item.materialId,
                },
            ];
            let processPlanInputNewList = processPlanInputList.map(item=>{
                const result = { ...item };
                if (item.inventoryType === 'C60') {
                    result.inputNumSixty = item.inputNum;
                } else if (item.inventoryType === 'C70') {
                    result.inputNumSeventy = item.inputNum;
                } else if (item.inventoryType === 'C90') {
                    result.inputNumNinety = item.inputNum;
                }
                result.id = ''
                return result;
            })
            processPlanDetailList.push({
                ...alarmDataItem,
                isPro: true,
                inputNum: num,
                processPlanInputNewList:processPlanInputNewList,
            });
        });
        if (!verfyType) {
            this.$message.error(verfyWords);
            return false;
        }

        if (total > item.surplus) {
            this.$message.error("包装计划投料数量不能大于库存量");
            return false;
        }

        return processPlanDetailList;
    }

    proNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            await this.getKeLiNum();
        }, 500);
    }
    needNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            await this.getProdNum();
        }, 500);
    }

    /**
     * 获取颗粒数量
     */
    async getKeLiNum() {
        try {
            this.loading = true;
            const alarmData = this.alarmDataCopy;
            let count = 0;
            let len = alarmData.length;

            alarmData.forEach(async (item, idx) => {
                const keliRes = await warningApi.getKeLiNum({
                    id: item.prodId,

                    num: item.prodNum || 0,
                    inventoryType: item.inventoryType,
                });
                alarmData[idx].needNum = keliRes.data.num;
                alarmData[idx].packSellDay = keliRes.data.sellDay;
                count++;
                if (count >= len) {
                    this.loading = false;
                    this.alarmDataCopy = alarmData;

                }
            });
        } finally {
            //
            
        }
    }
    async getProdNum() {
        try {
            this.loading = true;
            const alarmData = this.alarmDataCopy;
            let count = 0;
            let len = alarmData.length;

            alarmData.forEach(async (item, idx) => {
                const keliRes = await warningApi.getProdNum({
                    id: item.prodId,

                    num: item.needNum || 0,
                    inventoryType: item.inventoryType,
                });
                alarmData[idx].prodNum = toDecimalNoZero(keliRes.data.num);
                alarmData[idx].packSellDay = keliRes.data.sellDay;
                count++;
                if (count >= len) {
                    this.loading = false;
                    this.alarmDataCopy = alarmData;
                }
            });
        } finally {
            //
        }
    }
}
</script>
<style lang="scss" scoped>
    .filter-list{
        margin-right:20px !important;
    }
.planList-index {
    .planList-top {
        font-size: 16px;
        padding-bottom: 10px;
    }
    .planList-title {
        font-weight: bold;
        font-size: 20px;
    }

    .overview-panel {
        background-color: #fff;
        padding: 10px 10px;
    }
    .overview-title {
        margin-right: 30px;
    }
    .overview-titlebox {
        padding: 10px 0;
    }
}
</style>
